package org.robot.scm.platform.monitor;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.platform.AbstractMonitor;
import org.robot.scm.pojos.BaseNotify;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.pojos.platform.DebtsBaseNotify;
import org.robot.scm.pojos.platform.sqlite.MyDebts;
import org.robot.scm.utils.SQLiteUtil;
import org.robot.scm.utils.StreamUtils;

/**
 * 账务管理
 */
@Slf4j
public class DebtsNoticeMonitor extends AbstractMonitor {


    @Override
    public PlatformEnum getPlatform() {
        return PlatformEnum.DEBTS;
    }

    @SneakyThrows
    @Override
    public BaseNotify doMonitor(BaseConfig config) {
        // 当前是否10号，非10号不提醒
        LocalDate currentDate = LocalDate.now();
        int dayOfMonth = currentDate.getDayOfMonth();
        if (dayOfMonth != 10) {
            return null;
        }
        String date = currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        try {
            // 当前10号是否已经记账
            List<MyDebts> myDebts = SQLiteUtil.query("select * from my_debts", MyDebts.class);
            if (!StreamUtils.filter(myDebts, e -> StringUtils.equals(e.getDebtsDate(), date)).isEmpty()) {
                return null;
            }

            // 总账务 - 已记账务 - 当期账务 = 剩余账务
            Integer sumToInt = StreamUtils.sumToInt(myDebts, MyDebts::getDebtsAmount);
            Integer totalRemain = 680000 - sumToInt - 13000;
            MyDebts monthDebts = MyDebts.builder()
                    .debtsAmount(13000)
                    .debtsName("月度记账")
                    .debtsTotal(680000)
                    .debtsRemain(totalRemain)
                    .remark("系统生成")
                    .build();
            String result = SQLiteUtil.insert(monthDebts) ? "✅记账成功" : "❌记账失败";
            String template = "【记账日期】%s\n"
                    + "【记账期数】当前第%s期\n"
                    + "【记账金额】¥%s\n"
                    + "【记账总额】¥%s\n"
                    + "【记账余额】¥%s\n"
                    + "【记账结果】%s";
            String message = String.format(template, date, myDebts.size() + 1, monthDebts.getDebtsAmount(), monthDebts.getDebtsTotal(), monthDebts.getDebtsRemain(), result);
            log.info("debts result, date: {}, message: {}", date, message);
            return DebtsBaseNotify.builder()
                    .message(message)
                    .createDay(date)
                    .build();
        } catch (Exception e) {
            String template = "【记账日期】%s\n【记账结果】❌记账失败\n【异常信息】%s";
            String message = String.format(template, date, e.getMessage());
            return DebtsBaseNotify.builder()
                    .message(message)
                    .createDay(date)
                    .build();
        }
    }
}
